// src/composables/useEdit.ts
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { router } from '@/router/index'
import { useRoute } from 'vue-router'
import myaxios from '@/auth/auth.service'
import { useHome } from '@/components/composables/useHome'
import { showToastMessage } from "@/utils/message"

export interface CulturalRelicForm {
  name: string
  image: any[]
  dynasty: string
  country: string
  building_type: string
  other_building_type: string
  disease_types: string[]
  disease_image: any[]
  other_disease_types: string
  hasSpectrum: string
  hasThreeD: string
  spectrum_file: any[]
  threeD_file: any[]
  painting_theme: string
  painting_technique: string
  current_damage_status: string
  // 新增字段 👇
  pattern_types: string[]
  other_pattern_types: string
  composition_style: string[]
  other_composition_style: string
  dominant_colors: string[]
  other_dominant_colors: string
  human_pollution_details: string
  other_pollution_details: string
  disease_severity: string
}

export function useUpload() {
  const { choicesData } = useHome()
  const loading = ref(false)
  const error = ref('')
  const relicId = ref(0)
  const currentRelic = ref<any>({})
  const route = useRoute()
  const formRef = ref()
  const imageChanged = ref(false)

  // 表单数据模型
  const formData = reactive({
    culturalRelic: {
      name: '',
      image: [],
      dynasty: '',
      country: '',
      building_type: '',
      other_building_type: '',
      disease_types: [],
      other_disease_types: '',
      disease_image: [],
      hasSpectrum: '',
      hasThreeD: '',
      spectrum_file: [],
      threeD_file: [],
      painting_theme: '',
      painting_technique: '',
      current_damage_status: '',
      // 新增字段初始化 👇
      pattern_types: [],
      other_pattern_types: '',
      composition_style: [],
      other_composition_style: '',
      dominant_colors: [],
      other_dominant_colors: '',
      human_pollution_details: '',
      other_pollution_details: '',
      disease_severity: '',

    } as CulturalRelicForm,
  })
  const goToUser = () => {
    router.push('/personalinfo')
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }
  const gomainpage = () => {
    router.push({
      path: '/mainpage',
      query: { categoryid: route.query.categoryid, categoryname: route.query.categoryname },
    })
  }

  /**
   * 将选中的数组和“其他”输入框内容拼接成标准字符串
   * @param selected 已选的类型数组（可能包含 'other'）
   * @param otherValue “其他”输入框的内容
   * @param otherLabel 显示标签，如“其他”、“人为污染”等
   */
  const formatWithOther = (
    selected: string[],
    otherValue: string,
    otherLabel: string
  ): string => {
    if (!Array.isArray(selected)) return ''

    const result: string[] = []

    selected.forEach(item => {
      if (item === 'other' || item === '其他') {
        const val = otherValue?.trim()
        if (val) {
          result.push(`${otherLabel}:${val}`)
        }
        // 如果只有“其他”但无内容，只保留标签（可选）
        // else { result.push(otherLabel) }
      } else {
        result.push(item)
      }
    })

    return result.join(',')
  }
  const categoryname = route.query.categoryname
  const categoryid = route.query.categoryid

  // 自定义校验函数
  const validateImage = (): boolean => {
    if (currentRelic.value.image && !imageChanged.value) {
      return true
    }
    return formData.culturalRelic.image.length > 0
  }

  const validateBuildingType = (): boolean => {
    const buildingType = formData.culturalRelic.building_type
    if (!buildingType) {
      return false
    }
    if (buildingType === 'other') {
      return formData.culturalRelic.other_building_type.trim() !== ''
    }
    return true
  }

  /**
   * 校验病害类型（保留原有复杂逻辑）
   */
  const validateDiseaseTypes = (): boolean => {
    const { culturalRelic } = formData

    // 1. 至少选一个病害类型
    if (culturalRelic.disease_types.length === 0) {
      showToastMessage("warning", "请选择至少一种病害类型")
      return false
    }
    // 2. 检查“其他”是否有填写
    if (
      culturalRelic.disease_types.includes('other') &&
      !culturalRelic.other_disease_types?.trim()
    ) {
      showToastMessage("warning", "请说明“其他”病害的具体类型")
      return false
    }

    // 3. 检查“人为污染”是否有详细说明
    if (
      culturalRelic.disease_types.includes('人为污染') &&
      !culturalRelic.human_pollution_details?.trim()
    ) {
      showToastMessage("warning", "请详细描述“人为污染”的情况")
      return false
    }

    // 4. 检查“其他污染”是否有详细说明
    if (
      culturalRelic.disease_types.includes('其他污染') &&
      !culturalRelic.other_pollution_details?.trim()
    ) {
      showToastMessage("warning", "请详细描述“其他污染”的情况")
      return false
    }

    return true
  }

  const validateHasSpectrum = (): boolean => {
    return formData.culturalRelic.hasSpectrum !== ''
  }

  /**
   * 通用校验：检查是否选择了 'other' 但未填写对应输入框
   */
  const validateWithOther = (
    selected: string[],
    otherValue: string,
    fieldName: string
  ): boolean => {
    if (!Array.isArray(selected)) return false

    if (selected.includes('other') || selected.includes('其他')) {
      if (!otherValue?.trim()) {
        const msg=`请选择“${fieldName}”中的“其他”后填写具体内容`
        showToastMessage("info", msg)
        return false
      }
    }
    return true
  }

  /**
   * 统一校验所有复合型字段（带“其他”的多选字段）
   */
  const validateComplexFields = (): boolean => {
    const { culturalRelic } = formData

    // 1. 病害类型（使用原有复杂校验）
    if (!validateDiseaseTypes()) return false
    console.log("11")
    // 2. 痛样类型
    if (!validateWithOther(culturalRelic.pattern_types, culturalRelic.other_pattern_types, '纹样类型')) {
      return false
    }

    // 3. 构图形式
    if (!validateWithOther(culturalRelic.composition_style, culturalRelic.other_composition_style, '构图形式')) {
      return false
    }

    // 4. 主色调
    if (!validateWithOther(culturalRelic.dominant_colors, culturalRelic.other_dominant_colors, '主色调')) {
      return false
    }

    return true
  }

  // 图片上传变化处理
  const onImageChange = () => {
    imageChanged.value = true
  }

  // 表单校验失败处理
  const onFailed = (errorInfo: any) => {
    console.log('表单校验失败', errorInfo)
    showToastMessage("error", "请完善必填信息")
  }
  const onClickLeft = () => {
    router.go(-1)
  }

  const getRawFile = (fileItem) => {
    if (!fileItem) return null
    if (fileItem.file && fileItem.file instanceof File) return fileItem.file
    if (fileItem.raw && fileItem.raw instanceof File) return fileItem.raw
    if (fileItem instanceof File) return fileItem
    return null
  }

  // 取消编辑
  const handleCancel = () => {
    router.go(-1)
  }

  const handleDiseaseImageChange = (file: any, fileList: any[]) => {
    // 为每个文件添加自定义字段（如果还没有）
    fileList.forEach(item => {
      if (!item.customName) {
        item.customName = '' // 默认为空
      }
      if (!item.description) {
        item.description = ''
      }
    })
    // 更新 formData（v-model 会自动同步，但确保引用更新）
    formData.culturalRelic.disease_image = fileList
  }


  // 提交处理函数
  const onSubmit = async () => {
    if (loading.value) return

    // 使用统一校验函数
    if (!validateComplexFields()) return

    try {
      loading.value = true
      const form = new FormData()
      const { culturalRelic } = formData

      // --- 基础字段 ---
      form.append('name', culturalRelic.name)
      form.append('dynasty', culturalRelic.dynasty)
      form.append('country', culturalRelic.country)
      form.append('building_type', culturalRelic.building_type)
      form.append('other_building_type', culturalRelic.other_building_type)
      form.append('hasSpectrum', culturalRelic.hasSpectrum)
      form.append('hasThreeD', culturalRelic.hasThreeD)
      form.append('painting_theme', culturalRelic.painting_theme)
      form.append('current_damage_status', culturalRelic.current_damage_status)
      form.append('painting_technique', culturalRelic.painting_technique)
      form.append('disease_severity', culturalRelic.disease_severity)
      form.append('category_id', route.query.categoryid)

      // --- 复合字段拼接 ---
      form.append('pattern_types', formatWithOther(
        culturalRelic.pattern_types,
        culturalRelic.other_pattern_types,
        '其他'
      ))

      form.append('composition_style', formatWithOther(
        culturalRelic.composition_style,
        culturalRelic.other_composition_style,
        '其他'
      ))

      form.append('dominant_colors', formatWithOther(
        culturalRelic.dominant_colors,
        culturalRelic.other_dominant_colors,
        '其他'
      ))

      // --- 病害类型（特殊处理）---
      const parts: string[] = []
      culturalRelic.disease_types.forEach(type => {
        if (type === 'other') {
          const other = culturalRelic.other_disease_types?.trim()
          parts.push(other ? `其他:${other}` : '其他')
        } else if (type === '人为污染') {
          const detail = culturalRelic.human_pollution_details?.trim()
          parts.push(detail ? `人为污染:${detail}` : '人为污染')
        } else if (type === '其他污染') {
          const detail = culturalRelic.other_pollution_details?.trim()
          parts.push(detail ? `其他污染:${detail}` : '其他污染')
        } else {
          parts.push(type)
        }
      })
      form.append('disease_types', parts.join(','))

      // --- 图像与文件上传 ---
      if (culturalRelic.image.length > 0) {
        const rawFile = getRawFile(culturalRelic.image[0])
        if (rawFile && rawFile instanceof File) {
          form.append('image', rawFile)
          console.log('✅ 添加主图像:', rawFile.name)
        } else {
          console.error('❌ 主图像获取失败')
          showToastMessage("error", "主图像数据异常")
          return
        }
      }


      // --- 病害图像（批量）---
      const diseaseImageMetadatas = []
      if (Array.isArray(culturalRelic.disease_image)) {
        for (let i = 0; i < culturalRelic.disease_image.length; i++) {
          const item = culturalRelic.disease_image[i]
          const rawFile = item.raw || item.file

          if (rawFile instanceof File) {
            form.append('disease_images', rawFile)
            diseaseImageMetadatas.push({
              name: item.customName || item.image_name || '',
              description: item.description || ''
            })
          } else {
            console.warn(`⚠️ 病害图像[${i}]不是有效文件，跳过`)
          }
        }
      }
      if (diseaseImageMetadatas.length > 0) {
        form.append('disease_image_metadata', JSON.stringify(diseaseImageMetadatas))
      }



      if (culturalRelic.spectrum_file.length > 0) {
        const rawFile = getRawFile(culturalRelic.spectrum_file[0])
        if (rawFile && rawFile instanceof File) {
          form.append('spectrum_file', rawFile)
          console.log('✅ 添加光谱文件:', rawFile.name)
        }
      }

      if (culturalRelic.threeD_file.length > 0) {
        const rawFile = getRawFile(culturalRelic.threeD_file[0])
        if (rawFile && rawFile instanceof File) {
          form.append('threeD_file', rawFile)
          console.log('✅ 添加三维文件:', rawFile.name)
        }
      }

      // 调试输出
      console.log('📤 最终提交数据:', {
        pattern_types: form.get('pattern_types'),
        composition_style: form.get('composition_style'),
        dominant_colors: form.get('dominant_colors'),
        disease_types: form.get('disease_types'),
        disease_images: form.get('disease_images'),
        disease_image_metadata: form.get('disease_image_metadata'),
        all: form
      })

      const response = await myaxios.uploadData(form)
      showToastMessage("success", "提交成功")
      router.push({
        path: '/mainpage',
        query: { categoryid: route.query.categoryid, categoryname: route.query.categoryname },
      })

    } catch (e) {
      console.error('提交失败:', e)
      showToastMessage("error", "提交失败，请重试")
    } finally {
      loading.value = false
    }
  }

  return {
    choicesData,
    loading,
    error,
    relicId,
    currentRelic,
    formRef,
    formData,
    imageChanged,
    categoryid,
    categoryname,
    goToUser,
    goHome,
    goToCategory,
    gomainpage,
    validateImage,
    validateBuildingType,
    validateDiseaseTypes,
    validateHasSpectrum,
    validateComplexFields, // 👈 新增：统一校验函数
    onImageChange,
    onFailed,
    onClickLeft,
    onSubmit,
    handleCancel,
    handleDiseaseImageChange
  }
}
